import { ReactNode, useState } from 'react';
import { widgetManager } from '@/common/managers';
import { BaseCommand, cmdInvoker, InvokeCmdFunc, ObjInfo } from '@amcax/base';
import { userEvents } from 'nextcae-base';
import { ToolBarEvents } from '@/components/CmdBar/CmdBottomBtn/type';
// let oldCmdParam = null;
export const useInvoke = () => {
  const [currentCmd, setCurrentCmd] = useState<BaseCommand | null>(null);
  const [currentCmdProps, setCurrentCmdProps] = useState<ObjInfo | null>(null);
  const [cmdDialog, setCmdDialog] = useState<ReactNode | null>(null);
  const invokeCmd: InvokeCmdFunc = async (
    cmd: BaseCommand,
    props?: ObjInfo,
    customParams?: any,
    invokeCallback?: VoidFunction,
  ) => {
    const previousCmd = currentCmd;
    const previousCmdProps = currentCmdProps;
    userEvents.emit(ToolBarEvents.CMD_OPEN_CLOSE, {
      isOpen: true,
      id: cmd.id,
    });
    if (cmd.noHighlight) {
      setCurrentCmd(null);
      setCurrentCmdProps(null);
    } else {
      setCurrentCmd(cmd);
    }
    if (cmd.create) {
      setCurrentCmdProps(props);
      return new Promise<any>((resolve) => {
        setTimeout(() => {
          setCmdDialog(
            cmd.create(
              cmd.label,
              (result?: any) => {
                widgetManager.hint('');
                resolve(result);
                setCurrentCmd(null);
                setCmdDialog(null);
                userEvents.emit(ToolBarEvents.CMD_OPEN_CLOSE, {
                  isOpen: false,
                  id: cmd.id,
                });
                userEvents.emit(ToolBarEvents.ESC);
              },
              props,
              customParams,
            ),
          );
        }, 50);
      });
    } else if (cmd.invoke) {
      try {
        if (!cmd.standalone) {
          setCmdDialog(null);
        }

        const result = await cmd.invoke(invokeCallback);
        setCurrentCmd(null);

        if (cmd.standalone && previousCmd) {
          setCurrentCmd(previousCmd);
          setCurrentCmdProps(previousCmdProps);
        }

        return result;
      } catch (e) {
        console.error(e);
      }
    }
  };
  const resetCmd = () => {
    setCurrentCmdProps(null);
    setCmdDialog(null);
    setCurrentCmd(null);
  };

  cmdInvoker.invokeCmd = invokeCmd;
  cmdInvoker.resetCmd = resetCmd;
  return {
    currentCmdProps,
    currentCmd,
    invokeCmd,
    resetCmd,
    cmdDialog,
  };
};
